"use strict";

const utils = require('../utils/util');
const listenerEnums = {
	add: 'notify',
	remove: 'remove',
};

module.exports = {
	meta: {
		docs: {
			description: "notify listener lint",
			category: "Best Practices",
			recommended: false
		},
		fixable: null,
		schema: [
		]
	},
	create: function(context) {
		const notifyListeners = [], removeListeners = [];
		return {
			CallExpression(node) {
				const methodName = utils.getNotifyCallExpression(node);
				if (methodName === listenerEnums.add){
					const result = utils.isAssignExpression(node);
					if(!result || !result.assignVariable) {
						context.report(node, `onKPOSNotify必须用变量接收`);
					}
					if (result && result.assignVariable) {
						notifyListeners.push({
							assignVariable: result.assignVariable,
							node,
						});
					}
					return;
				}
				const result = utils.getMemberCallExpression(node);
				if (result.methodName === listenerEnums.remove) {
					removeListeners.push({
						assignVariable: result.targetObj,
						node,
					});
				}
			},
			'Program:exit'() {
				if	(notifyListeners.length > 0) {
					notifyListeners.forEach(listener => {
						const removceListener = removeListeners.find(item => item.assignVariable === listener.assignVariable);
						if (!removceListener) {
							context.report(listener.node, `请别忘记移除${listener.assignVariable}的notify监听`);
						}
					});
				}
			},
		};
	}
};